<?php

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'service/AlipayTradeService.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'buildermodel/AlipayTradeWapPayContentBuilder.php';
require_once dirname(__FILE__) .  DIRECTORY_SEPARATOR . 'buildermodel/AlipayTradeQueryContentBuilder.php';
require_once dirname(__FILE__) .   DIRECTORY_SEPARATOR .'buildermodel/AlipayTradeRefundContentBuilder.php';
class alipay_h5 {

    //配置
    private $alipay_config = array();

    public function __construct($param = array()) {
        if (!empty($param)) {
            $this->alipay_config = array(
                //应用ID,您的APPID。
                'app_id' => $param['payment_config']['alipay_appid'],
                //商户私钥，您的原始格式RSA私钥
                'merchant_private_key' => $param['payment_config']['private_key'],
                //异步通知地址
                'notify_url' => str_replace('/index.php', '', HOME_SITE_URL) . '/payment/alipay_h5_notify.html',
                //编码格式
                'charset' => "UTF-8",
                //签名方式
                'sign_type' => "RSA2",
                //支付宝网关
                'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
                //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
                'alipay_public_key' => $param['payment_config']['public_key'],
            );
        }
    }

    public function get_payform($order_info) {
        $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($order_info['order_type']);
        $payRequestBuilder->setSubject($order_info['subject']);
        $payRequestBuilder->setOutTradeNo($order_info['order_type'] . '-' . $order_info['pay_sn']);
        $payRequestBuilder->setTotalAmount($order_info['api_pay_amount']);
        $payRequestBuilder->setTimeExpress('1m');

        $payResponse = new AlipayTradeService($this->alipay_config);
        //不同订单支付成功对应的跳转界面
        if($order_info['order_type'] == 'real_order'){
            $url = H5_SITE_URL.'/member/order_list';
        }elseif ($order_info['order_type'] == 'vr_order') {
            $url = H5_SITE_URL.'/member/vrorder_list';
        } elseif ($order_info['order_type'] == 'pd_order') {
            $url = H5_SITE_URL.'/member/recharge_list';
        }
        $result = $payResponse->wapPay($payRequestBuilder, $url, $this->alipay_config['notify_url']);
        return;
    }

    /**
     * 获取return信息
     */
    public function verify_return() {
        $arr = $_GET;
        $alipaySevice = new AlipayTradeService($this->alipay_config);
        $result = $alipaySevice->check($arr);
        if ($result) {
            return true;
        }
        return false;
    }


	public function verify_notify() {
		$arr = $_POST;
		$notify_result = array(
			'trade_status' => '0',
		);
		$alipaySevice = new AlipayTradeService($this->alipay_config);
		$alipaySevice->writeLog('verify_notify' . var_export($arr, true));
		$result = $alipaySevice->check($arr);
		if ($result) {
			if ($arr['trade_status'] == 'TRADE_SUCCESS') {
				$out_trade_no = explode('-', input('param.out_trade_no'));
				$out_trade_no = $out_trade_no['1'];
				$notify_result = array(
					'out_trade_no' => $out_trade_no, #商户订单号
					'trade_no' => input('param.trade_no'), #交易凭据单号
					'total_fee' => input('param.total_amount'), #涉及金额
					'order_type' => input('param.body'),
					'trade_status' => '1',
				);
			}
		}
		return $notify_result;
	}



	/**
	 * 原路退款
	 */
	public function trade_refund($order_info,$refund_amount)
	{
		//构造参数
		$RequestBuilder = new AlipayTradeRefundContentBuilder();

		//setOutTradeNo  setOutRequestNo
		$RequestBuilder->setTradeNo($order_info['trade_no']);
		$RequestBuilder->setRefundAmount($refund_amount);
		$RequestBuilder->setRefundReason('订单退款');
		$RequestBuilder->setOutRequestNo($order_info['out_request_no']);//支付宝部分退款必传唯一的标识一次退款请求号

		$aop = new AlipayTradeService($this->alipay_config);
		$response = $aop->Refund($RequestBuilder);

		if($response->code == 10000){
			return ds_callback(TRUE, $response->msg);
		}else{
			return ds_callback(FALSE, $response->msg);
		}

		/*
object(stdClass)#41 (10) {
  ["code"] => string(5) "10000"
  ["msg"] => string(7) "Success"
  ["buyer_logon_id"] => string(14) "l***@126.com"
  ["buyer_user_id"] => string(16) "2088002237181934"
  ["fund_change"] => string(1) "Y"
  ["gmt_refund_pay"] => string(19) "2019-09-19 16:06:01"
  ["out_trade_no"] => string(31) "real_order-19091911525456613013"
  ["refund_fee"] => string(4) "0.01"
  ["send_back_fee"] => string(4) "0.00"
  ["trade_no"] => string(28) "2019091922001481930549025169"
}
		 */
	}

}
